<template>
  <!-- 对话框组件嵌套了一个form表单 -->
  <el-dialog
    :model-value="true"
    :title="title"
    width="500px"
    :before-close="handleClose"
    draggable="true"
  >
    <!-- 显示商品详情的表单组件 -->
    <el-form
      ref="formRef"
      :model="createForm"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item prop="ID" label="商品序号:" v-if="idShow">
        {{ createForm.ID }}
      </el-form-item>
      <el-form-item label="商品名称" prop="name" required>
        <el-input
          v-model.trim="createForm.name"
          placeholder="输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="level" required>
        <el-input
          v-model.number="createForm.level"
          placeholder="输入数量"
        ></el-input>
      </el-form-item>
      <el-form-item label="单价" prop="price" required>
        <el-input
          v-model="createForm.price"
          placeholder="输入单价"
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否上架" required>
        <el-switch v-model="createForm.onSale"></el-switch>
      </el-form-item>
      <el-form-item label="添加时间">
        <el-col :span="9">
          <el-form-item>
            <el-date-picker
              v-model="date1"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2"> &nbsp;&nbsp;&nbsp;- </el-col>
        <el-col :span="10">
          <el-form-item>
            <el-time-picker
              v-model="date2"
              placeholder="选择时间"
              style="width: 100%"
            ></el-time-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="createForm.remark"
          placeholder="输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 对话框底部组件 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleConfirm" type="primary">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import { insertData, updateData } from '@/apis/data/userData.js'
export default {
  name: 'dialog',
  props: ['title', 'upDateData'],
  data() {
    return {
      idShow: false,
      date2: null,
      date1: null,
      createForm: {
        ID: null,
        name: '',
        price: null,
        level: null,
        onSale: false,
        remark: '',
        createTime: null,
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if ([...value].length > 10) {
                callback(new Error('输入商品字符不能超过10个'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        level: [
          {
            required: true,
            message: '请输入数字，且为正整数',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0 || value >= 1000 || !/(^[1-9]\d*$)/.test(value)) {
                callback(new Error('输入数据不合法,请输入小于1000的正整数'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        price: [
          {
            required: true,
            message: '金额不能为空',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^[-\+]?\d{0,8}\.{0,1}(\d{1,2})?$/.test(value)) {
                callback(new Error('输入数据不合法,请输入正确的金额'))
              } else if (value <= 0 || value >= 1000) {
                callback(new Error('单价不能超过1000!'))
              } else {
                this.createForm.price = Number(value)
                callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        remark: {
          validator: (rule, value, callback) => {
            if ([...value].length > 20) {
              callback(new Error('输入字符不能超过20个'))
            } else {
              callback()
            }
          },
          trigger: ['change', 'blur'],
        },
      },
    }
  },
  created() {
    if (!this.upDateData) {
      console.log('没有拿到值', this.upDateData)
      return
    } else {
      this.idShow = true
      for (const k in this.upDateData) {
        if (this.upDateData[k] == '是') {
          this.createForm.onSale = true
          continue
        }
        if (
          typeof this.upDateData[k] == 'string' &&
          this.upDateData[k].indexOf('-') != -1
        ) {
          this.date1 = new Date(this.upDateData[k])
          this.date2 = new Date(this.upDateData[k])
          console.log(this.date2)
        }
        this.createForm[k] = this.upDateData[k]
      }
    }
  },
  methods: {
    handleClose() {
      ElMessageBox.confirm('您有数据未保存，确定关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log(this.createForm)
          this.$emit('closeDialog')
        })
        .catch(() => {
          console.log(this.createForm)
        })
    },
    //处理时间的函数
    mergeTime(date1, date2) {
      let year = date1.getFullYear()
      let month = date1.getMonth()
      let day = date1.getDay()
      let hours = date2.getHours()
      let minutes = date2.getMinutes()
      let seconds = date2.getSeconds()
      let milliseconds = date2.getMilliseconds()
      let mergeTime = new Date(
        year,
        month,
        day,
        hours,
        minutes,
        seconds,
        milliseconds
      )
      return mergeTime
    },
    handleConfirm() {
      // 根据id的有无来判断是否是跟新，还是创建
      if (this.createForm.ID) {
        this.onUpdate()
      } else {
        this.onCreate()
      }
    },
    //更新函数
    onUpdate() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 提交更新到后台
          this.createForm.createTime = this.mergeTime(this.date1, this.date2)
          updateData(this.createForm)
            .then((res) => {
              if (res.code == 200) {
                this.$emit('closeDialog')
                this.$message({
                  message: '更新商品成功',
                  type: 'success',
                  showClose: true,
                })
              }
            })
            .catch((err) => {
              this.$message({
                message: '更新商品失败，请重新添加！',
                type: 'error',
                showClose: true,
              })
              console.log(err.Error)
              return false
            })
        } else {
          this.$message({
            message: '请输入正确的表单项',
            type: 'waring',
            showClose: true,
          })
          return false
        }
      })
    },
    // 创建函数
    onCreate() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 提交添加到后台
          this.createForm.createTime = this.mergeTime(this.date1, this.date2)
          insertData(this.createForm)
            .then((res) => {
              if (res.code == 200) {
                console.log(res.data)
                this.$emit('closeDialog')
                this.$message({
                  message: '添加商品成功',
                  type: 'success',
                  showClose: true,
                })
              }
            })
            .catch((err) => {
              this.$message({
                message: '新增商品失败，请重新添加！',
                type: 'error',
                showClose: true,
              })
              console.log(err.Error)
              return false
            })
        } else {
          this.$message({
            message: '请输入正确的表单项',
            type: 'waring',
            showClose: true,
          })
          return false
        }
      })
    },
  },
}
</script>
